﻿#include "phRenWorker.h"
#include <QFile>
#include <QDir>
#include <QDirIterator>

phRenWorker::phRenWorker(QObject *parent) : QObject(parent)
{
    moveToThread(&thd);
    connect(this, SIGNAL(rename(QString)),
            this, SLOT(doRename(QString)), Qt::QueuedConnection);

    thd.start();
}

phRenWorker::~phRenWorker()
{
    thd.quit();
}

void phRenWorker::doRename(QString path)
{
    QDir dir(path);
    int cnt = 0;
    QString msg;

    if(!dir.exists())
    {
        return;
    }

    QStringList filters;
    filters<<QString("*.jpeg")<<QString("*.jpg");

    QDirIterator dir_iterator(path,
                              filters,
                              QDir::Files | QDir::NoSymLinks,
                              QDirIterator::Subdirectories);

    emit msgout("处理中");
    while(dir_iterator.hasNext())
    {
        dir_iterator.next();

        QFileInfo fi = dir_iterator.fileInfo();

        if (_rename(fi.absolutePath(), fi.fileName()))
            cnt ++;
    }

    msg = msg.sprintf("处理结束%d", cnt);
    emit msgout(msg);
}

bool phRenWorker::_rename(QString path, QString name)
{
    QStringList list;
    QStringList nml;
    bool ret = false;
    int cnt;
    QString spf;

    list = path.split("/");
    cnt = list.count();
    nml = name.split("_");

    path += "/";

    if (nml.count() == 3)
    {
        QString newnm;
        QString on, nn;
        QFile d;
        spf = list.at(cnt - 1);

        if (spf == nml.at(0))
        {
            spf = "0";
        }
        else if (spf.size() != 1)
            return ret;

        newnm = nml.at(0) + "_" +
                nml.at(1) + "_" +
                spf + "_" +
                nml.at(2);
        on = path + name;
        nn = path + newnm;
        d.setFileName(on);
        ret = d.rename(nn);
        //QFile::remove(on);
    }

    return ret;
}
